package com.chima.action;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.chima.domain.Department;
import com.chima.domain.DetailJob;
import com.chima.domain.Employees;
import com.chima.domain.TastJob;
import com.chima.service.DepartmentService;
import com.chima.service.DetailJobService;
import com.chima.service.EmployeeService;
import com.chima.service.TastJobService;
import com.opensymphony.xwork2.ActionSupport;
import flexjson.JSONSerializer;
import flexjson.transformer.DateTransformer;

public class DetailJobAction extends ActionSupport {
	private DetailJobService detailJobService;
	private TastJobService  tastJobService;
	private EmployeeService employeeService;
	private DepartmentService departmentService;
	private int id;
	private String emp;
	private String depart;
	private String  name;
	private Date  startdate;
	private Date  planCompleteDate;
	private String  had;
	private TastJob tastJob;
	private int   state; 
	private String jobRequirement;
	private String  upload;
	private String uploadContentType;
	private String uploadFileName;
	private String huifu;
	private double deptbili;
	
	public double getDeptbili() {
		return deptbili;
	}

	public void setDeptbili(double deptbili) {
		this.deptbili = deptbili;
	}

	public String getHuifu() {
		return huifu;
	}

	public void setHuifu(String huifu) {
		this.huifu = huifu;
	}

	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}

	public void setDepartmentService(DepartmentService departmentService) {
		this.departmentService = departmentService;
	}

	public String getJobRequirement() {
		return jobRequirement;
	}

	public void setJobRequirement(String jobRequirement) {
		this.jobRequirement = jobRequirement;
	}

	public String getEmp() {
		return emp;
	}

	public void setEmp(String emp) {
		this.emp = emp;
	}

	public String getDepart() {
		return depart;
	}

	public void setDepart(String depart) {
		this.depart = depart;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	

	public Date getStartdate() {
		return startdate;
	}

	public void setStartdate(Date startdate) {
		this.startdate = startdate;
	}

	public Date getPlanCompleteDate() {
		return planCompleteDate;
	}

	public void setPlanCompleteDate(Date planCompleteDate) {
		this.planCompleteDate = planCompleteDate;
	}

	public String getHad() {
		return had;
	}

	public void setHad(String had) {
		this.had = had;
	}

	public TastJob getTastJob() {
		return tastJob;
	}

	public void setTastJob(TastJob tastJob) {
		this.tastJob = tastJob;
	}

	public int getState() {
		return state;
	}

	public void setState(int state) {
		this.state = state;
	}

	public String getUpload() {
		return upload;
	}

	public void setUpload(String upload) {
		this.upload = upload;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	private boolean success=false;
	public int getId() {
		return id;
	}
	
	public void setTastJobService(TastJobService tastJobService) {
		this.tastJobService = tastJobService;
	}

	public void setId(int id) {
		this.id = id;
	}

	public void setDetailJobService(DetailJobService detailJobService) {
		this.detailJobService = detailJobService;
	}
	public String listDetailJobsByJob() throws Exception{
		List<DetailJob> detailJobs=detailJobService.findDetailJobByJobId(id);
		int total= detailJobs.size();
		    JSONSerializer jsonSerializer = new JSONSerializer();
	        jsonSerializer.exclude("*.class");
	        jsonSerializer.transform(new DateTransformer("yyyy-MM-dd"),Date.class);
	        String resultJson1 = jsonSerializer.deepSerialize(detailJobs);
	        String resultJson2 =jsonSerializer.serialize(total);
	        String jsonString = "{total:"+resultJson2.toString()+",detailJobs:"+resultJson1.toString()+"}";
			ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
			ServletActionContext.getResponse().getWriter().print(jsonString);
		
		return NONE;
		
	}
	public String addDetailJob() throws Exception{
		TastJob tastJob=tastJobService.findTastJobbyId(id);
		  if(tastJob.getState()==1){
			this.success=true;
			JSONSerializer jsonSerializer = new JSONSerializer();
			String resultJson =jsonSerializer.serialize(success);
			String jsonString = "{success:"+resultJson.toString()+"}";
			ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
			ServletActionContext.getResponse().getWriter().print(jsonString);  
		  }else{
			  throw new RuntimeException("项目正在办理中");
		  }
			return NONE;
		
	 }
	public String deleteDetailJob() throws Exception{
		TastJob tastJob=tastJobService.findTastJobbyId(id);
		  if(tastJob.getState()==1){
			this.success=true;
			JSONSerializer jsonSerializer = new JSONSerializer();
			String resultJson =jsonSerializer.serialize(success);
			String jsonString = "{success:"+resultJson.toString()+"}";
			ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
			ServletActionContext.getResponse().getWriter().print(jsonString);  
		  }else{
			  throw new RuntimeException("项目正在办理中");
		  }
			return NONE;
		
	 }
	
	public String addDetails() throws Exception{
		 String FileName=null;
			// 添加附件
		   if(upload!=null){
			   ServletContext servletContext = ServletActionContext.getServletContext();
				String uploadDir = servletContext.getRealPath("/upload");
				// 写文件
				SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
				String someFileName = sdf1.format(new Date()) + uploadFileName;
				FileName=someFileName;
				InputStream in = new BufferedInputStream(new FileInputStream(upload));
				OutputStream out = new BufferedOutputStream(new FileOutputStream(new File(uploadDir,someFileName)));// 真实文件名
				int b;
				while((b= in.read())!=-1){
					out.write(b);
				}
				in.close();
				out.close(); 
		   }
		   // 添加多个人时
		   List<String> departments=new ArrayList<String>();
		   List<String> persons=new ArrayList<String>();
		   List<String> bilis=new ArrayList<String>();
		  if(!had.equals("")){
			  String[] strings=had.split(",");
				for(int i=0;i<strings.length;i++){
						String aString=strings[i];
						String a=strings[i].replace("[","").replace("]","");
						String[] strings1=a.split("-");
							departments.add(strings1[0]);
							persons.add(strings1[1]);
							bilis.add(strings1[2]);
						}
				 }
		  TastJob t=detailJobService.findTastJobByJobId(tastJob.getId());
		  if(departments.size()>0&&persons.size()>0){
			
			  for(int i=0;i<persons.size();i++){ 
				  Employees employees=	employeeService.findEmployeesByName(persons.get(i));
				  Department department=departmentService.findByName(departments.get(i));
				  double  deptbili=Double.parseDouble( bilis.get(i));
				  DetailJob d= new DetailJob();
				  d.setName(name);
				  d.setEmployee(employees);
				  d.setDepartment(department);
				  d.setJobRequirement(jobRequirement);
				  d.setPlanCompleteDate(planCompleteDate);
				  d.setStartdate(startdate);
				  if(FileName!=null){
					  d.setFujian(FileName);
				  }
				  d.setShu(1);
				  d.setCore(t.getCore()*deptbili/100);
				  d.setState("1");
				  d.setTastJob(tastJob);
				  detailJobService.addDetailJob(d);
//				  this.success=true;
//					JSONSerializer jsonSerializer = new JSONSerializer();
//					String resultJson =jsonSerializer.serialize(success);
//					String jsonString = "{success:"+resultJson.toString()+"}";
//					ServletActionContext.getResponse().setContentType("text;charset=utf-8");
//					ServletActionContext.getResponse().getWriter().print(jsonString);
			  }
			   
		  }if(!emp.equals("请选择人员")&&!depart.equals("请选择科室")&& !emp.equals("")&&!depart.equals("") ){
			  Employees employees=	employeeService.findEmployeesByName(emp);
			  Department department=departmentService.findByName(depart);
//			  TastJob t=detailJobService.findTastJobByJobId(tastJob.getId());
			  DetailJob d= new DetailJob();
			  d.setName(name);
			  d.setEmployee(employees);
			  d.setDepartment(department);
			  d.setCore(deptbili/100*t.getCore());
			  d.setJobRequirement(jobRequirement);
			  d.setPlanCompleteDate(planCompleteDate);
			  d.setStartdate(startdate);
			  if(FileName!=null){
				  d.setFujian(FileName);
			  }
			  d.setShu(1);
			  d.setState("1");
			  d.setTastJob(tastJob);
			  detailJobService.addDetailJob(d);
		  }
		  this.success=true;
			JSONSerializer jsonSerializer = new JSONSerializer();
			String resultJson =jsonSerializer.serialize(success);
			String jsonString = "{success:"+resultJson.toString()+"}";
			ServletActionContext.getResponse().setContentType("text;charset=utf-8");
			ServletActionContext.getResponse().getWriter().print(jsonString);
			return NONE;
		
	 }
	public String listDetailJobsByState() throws Exception{
		List<DetailJob> Jobs =new ArrayList<DetailJob>();
		 Employees  existEmployee =(Employees) ServletActionContext.getRequest().getSession().getAttribute("existEmployee");
		 if(!existEmployee.getName().equals("admin")){
				List<DetailJob> detailJobs=detailJobService.findDetailJobByEmpAndState(existEmployee.getId(), "3");
				for(DetailJob d:detailJobs){
					if(d.getTastJob().getState()==2){
						  Jobs.add(d);
					}
				}
		 }
	    	int total= Jobs.size();
		    JSONSerializer jsonSerializer = new JSONSerializer();
	        jsonSerializer.exclude("*.class");
	        jsonSerializer.transform(new DateTransformer("yyyy-MM-dd"),Date.class);
	        String resultJson1 = jsonSerializer.deepSerialize(Jobs);
	        String resultJson2 =jsonSerializer.serialize(total);
	        String jsonString = "{total:"+resultJson2.toString()+",detailJobs:"+resultJson1.toString()+"}";
			ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
			ServletActionContext.getResponse().getWriter().print(jsonString);
		
		return NONE;
		
	}
	public String banli() throws Exception{
		DetailJob detailJob=detailJobService.findDetailJobById(id);
		  if(detailJob.getState().equals("1")){
			  detailJob.setState("2");
				detailJobService.updateDetailJob(detailJob);
				this.success=true;
				JSONSerializer jsonSerializer = new JSONSerializer();
				String resultJson =jsonSerializer.serialize(success);
				String jsonString = "{success:"+resultJson.toString()+"}";
				System.out.println(jsonString);
				ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
				ServletActionContext.getResponse().getWriter().print(jsonString);  
		  }else{
			  throw new RuntimeException("项目正在办理中");
		  }
			return NONE;
		
	 }
	public String huifu() throws Exception{
		      DetailJob detailJob=detailJobService.findDetailJobById(id);
		      detailJob.setHuifu(huifu);
		      detailJobService.updateDetailJob(detailJob);
				this.success=true;
				JSONSerializer jsonSerializer = new JSONSerializer();
				String resultJson =jsonSerializer.serialize(success);
				String jsonString = "{success:"+resultJson.toString()+"}";
				System.out.println(jsonString);
				ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
				ServletActionContext.getResponse().getWriter().print(jsonString);  
			return NONE;
	}
	public String wancheng() throws Exception{
		int all=0;
		DetailJob detailJob=detailJobService.findDetailJobById(id);
		 if(detailJob.getState().equals("2")){
			    Date d=new Date();
			    if(d.getTime()>detailJob.getPlanCompleteDate().getTime()){
			    	detailJob.setHandleState("2");
			    }else{
			    	detailJob.setHandleState("1");
			    }
			    detailJob.setActualCompleteDate(d);
			   
			    detailJob.setState("3");
				detailJobService.updateDetailJob(detailJob);
				TastJob job=tastJobService.findTastJobbyId(id);
				List<DetailJob>jobDetails=detailJobService.findDetailJobByJobId(id);
				for(int i=0;i<jobDetails.size();i++){
					if(jobDetails.get(i).getState().equals("3")){
						all=all+1;
					}
					if(all==jobDetails.size()){
						
						job.setState(3);
						tastJobService.updateTastJob(job);	
					}
				}
				this.success=true;
				JSONSerializer jsonSerializer = new JSONSerializer();
				String resultJson =jsonSerializer.serialize(success);
				String jsonString = "{success:"+resultJson.toString()+"}";
				System.out.println(jsonString);
				ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
				ServletActionContext.getResponse().getWriter().print(jsonString);
		  }else{
			  throw new RuntimeException("项目还未办理");
		  }
		return NONE;
		
	 }
	//下载附件
public String download () {
		DetailJob detailJob=detailJobService.findDetailJobById(id);
		
	    if(detailJob!=null){
	    	if(null==detailJob.getFujian()){
	    		  throw new RuntimeException("无附件可以下载");
	    	}
	    	
	    } 
		return NONE;
	}
public String downloadfujian () {
		  
		DetailJob j=detailJobService.findDetailJobById(id);
       
         String filename=j.getFujian();
	try {
		    ServletContext servletContext = ServletActionContext.getServletContext();
			String downloadDir = servletContext.getRealPath("/upload");
			//处理中文 GBK ISO-8859-1
			String cnData = filename.substring(0,filename.lastIndexOf("."));
			// 处理
			cnData = new String(cnData.getBytes("GBK"),"ISO-8859-1");
			
			String extName = filename.substring(filename.lastIndexOf("."));
			
			BufferedInputStream bs=new BufferedInputStream(new FileInputStream(new File(downloadDir, filename)));
			
			HttpServletResponse response = ServletActionContext.getResponse();
			OutputStream os = response.getOutputStream();// 取得输出流
			byte buffBytes[] = new byte[1024];
		
			response.reset();// 清空输出流
			// 设定输出文件头
			response.setHeader("Content-disposition", "attachment; filename="+ cnData + extName);
			response.setContentType("application/octet-stream;charset=UTF-8");
			int read = 0;
			while ((read = bs.read(buffBytes)) != -1) {
				os.write(buffBytes, 0, read);
			}
			os.flush();
			os.close();
			bs.close();
	} catch (Exception e) {
		
		e.printStackTrace();
	}
		return NONE;
	}
// 添加详情取消删除
	public String deleteByJobId() throws Exception{
		try {
			detailJobService.deletDetailJobByJob(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.success=true;
		JSONSerializer jsonSerializer = new JSONSerializer();
		String resultJson =jsonSerializer.serialize(success);
		String jsonString = "{success:"+resultJson.toString()+"}";
		System.out.println(jsonString);
		ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
		ServletActionContext.getResponse().getWriter().print(jsonString);
		return NONE;
	}
	public String deleteById() throws Exception{
		try {
			detailJobService.deletDetailJob(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.success=true;
		JSONSerializer jsonSerializer = new JSONSerializer();
		String resultJson =jsonSerializer.serialize(success);
		String jsonString = "{success:"+resultJson.toString()+"}";
		System.out.println(jsonString);
		ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
		ServletActionContext.getResponse().getWriter().print(jsonString);
		return NONE;
	}
	
}
